package ch.fhnw.edu.rental.daos.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ch.fhnw.edu.rental.daos.UserDAO;
import ch.fhnw.edu.rental.model.User;


public class JpaUserDAO implements UserDAO, ManagedDAO<User> {
	
	@PersistenceContext
	private EntityManager em;

	@Override
	public User getById(Long id) {
		return this.em.find(User.class, id);
	}

	@Override
	public List<User> getByName(String name) {
		Query q = this.em.createQuery("from User u where u.lastName = :name");
		q.setParameter("name", name);
		return q.getResultList();
	}

	@Override
	public List<User> getAll() {
		Query q = this.em.createQuery("from User m");
		return q.getResultList();
	}

	@Override
	public void saveOrUpdate(User user) {
		if (null == user.getId()) {
			this.em.persist(user);
		} else {
			this.em.merge(user);
		}
	}

	@Override
	public void delete(User user) {
		this.em.remove(user);
	}

	@Override
	public User manage(User instance) {
		return em.merge(instance);
	}
}
